package org.jeecg.modules.gis.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geometry.jts.WKBReader;
import org.jeecg.modules.gis.service.impl.DataManagerServiceImpl;

import org.jeecg.modules.gis.util.ShapefileTableBuilder;
import org.locationtech.jts.geom.Geometry;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Blob;
import java.sql.Struct;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/gis")
public class DataManagerController {

    @Autowired
    private DataManagerServiceImpl dataManagerServiceImpl;

    @GetMapping("/getGeomTables")
    public List<String> getGeomTables() {
        List<String> tables = dataManagerServiceImpl.getGeomTables();
        return tables;
    }
    @GetMapping("/getFeatureCollection")
    public JSONObject getFeatureCollection(@RequestParam String tableName) throws Exception {
        JSONObject fc = dataManagerServiceImpl.getFeatureCollection(tableName);
        return fc;
    }
    @PostMapping("/shapefile")
    public Map<String, Object> uploadShapefile(@RequestParam("files") MultipartFile[] files) throws IOException {
        Map<String, Object> result = new HashMap<>();

        if (files == null || files.length == 0) {
            result.put("success", false);
            result.put("message", "未上传任何文件");
            return result;
        }

        String uploadRootDir = System.getProperty("java.io.tmpdir") + "/gisworkspace/uploaddata";
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        Path targetDir = Paths.get(uploadRootDir, uuid);
        Files.createDirectories(targetDir);

        for (MultipartFile file : files) {
            if (file.isEmpty()) continue;

            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) continue;

            Path savePath = targetDir.resolve(originalFilename);
            file.transferTo(savePath.toFile());
            log.info("保存文件: {}", savePath);
        }

        try {
            Optional<Path> shpPathOpt = Files.list(targetDir)
                    .filter(p -> p.toString().toLowerCase().endsWith(".shp"))
                    .findFirst();

            if (!shpPathOpt.isPresent()) {
                result.put("success", false);
                result.put("message", "上传文件中未包含 .shp 文件");
                return result;
            }

            File shpFile = shpPathOpt.get().toFile();
            Map<String, Object> map = new HashMap<>();
            map.put("url", shpFile.toURI().toURL());
            DataStore dataStore = DataStoreFinder.getDataStore(map);

            if (dataStore == null) {
                result.put("success", false);
                result.put("message", "无法读取上传的shapefile");
                return result;
            }

            String typeName = dataStore.getTypeNames()[0];
            SimpleFeatureSource source = dataStore.getFeatureSource(typeName);
            dataManagerServiceImpl.createTableByShp(source, typeName);
            dataStore.dispose();

            result.put("success", true);
            result.put("message", "上传成功");
            return result;

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "解析shapefile时发生错误：" + e.getMessage());
            return result;

        } finally {
            // 删除临时目录及内容
            deleteDirectoryRecursively(targetDir);
            log.info("临时目录已删除: {}", targetDir);
        }
    }


    private void deleteDirectoryRecursively(Path path) throws IOException {
        if (Files.exists(path)) {
            Files.walk(path)
                    .sorted(Comparator.reverseOrder())
                    .map(Path::toFile)
                    .forEach(File::delete);
        }
    }
    @GetMapping("/download")
    public void download(@RequestParam String tableName,
                         @RequestParam String fileType,
                         HttpServletResponse response) {

        try {
            byte[] fileBytes;
            String fileName;
            String contentType;

            if ("shp".equalsIgnoreCase(fileType)) {
                // 使用已有的 shpZip 文件
                File shpZip = dataManagerServiceImpl.exportShpZip(tableName);
                fileBytes = Files.readAllBytes(shpZip.toPath());
                fileName = tableName + ".zip";
                contentType = "application/zip";
            } else if ("geojson".equalsIgnoreCase(fileType)) {
                // 导出为 GeoJSON 文件
                // byte[] geoJsonBytes = exportAsGeoJson(tableName);
                // 示例：假设你有 exportAsGeoJson 方法
                fileBytes = dataManagerServiceImpl.exportAsGeoJson(tableName);
                fileName = tableName + ".geojson";
                contentType = "application/json";
            } else {
                throw new IllegalArgumentException("不支持的文件类型：" + fileType);
            }

            // 设置响应头
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.getOutputStream().write(fileBytes);
            response.flushBuffer();

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }



    @GetMapping("/test")
    public String test() {

        return "测试成功";
    }

}
